import 'package:flutter/material.dart';

class FutureDemo extends StatefulWidget {
  FutureDemo({Key key}) : super(key: key);

  _FutureDemoState createState() => _FutureDemoState();
}

class _FutureDemoState extends State<FutureDemo> {
  Future _handlefuture() async {
    Future.delayed(Duration(seconds: 3), () {
      // 抛出异常 走catchError；
      // throw 'something wrong';
      return 111;
    })
        // 设置网络请求超时时间
        .timeout(Duration(seconds: 4))
        .then((res) {
      print(res);
    })
        // 网络请求完成触发（无论成功还是失败）
        .whenComplete(() {
      print('whenComplete');
    })
        // 抛出异常时触发
        .catchError((error) {
      print('$error');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FutureDemo'),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: _handlefuture,
              child: Text('further 按钮'),
            ),
          ],
        ),
      ),
    );
  }
}
